package com.android.base.thread;

import android.os.Handler;
import android.os.Message;


/**
 *@Project Name:	AndroidCommon
 *@Copyright:		
 *@Version:		1.0.0.1
 *@File_Name:		CustomerRunnable.java	
 *@AuthorName		Sammie.Zhang
 *@CreateDate:		2014-1-22
 *@ModifyHistory:
 */
public class CustomRunnable<T> implements Runnable {
	private IThreadAction<T> mAction;
	private T mReturnObj;
	private Thread mThread;
	private boolean mIsCanceled;

	public CustomRunnable(IThreadAction action){
		mAction = action;
	}
	@Override
	public void run() {
		try{
			if(null != mAction){
				mReturnObj = mAction.doInBackground();
			}
			handler.sendEmptyMessage(0);
		}catch(Exception ex){
			ex.printStackTrace();
			handler.sendEmptyMessage(0);
		}
	}
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(!mIsCanceled)
				mAction.returnForeground(mReturnObj);
		}
	};

	public void startAction(){
		mThread = new Thread(this);
		mThread.start();
	}
	public void cancel(){
		if(null != mAction) {
			mIsCanceled = true;
			mAction.cancel();
		}
	}
}
